﻿(function () {
    'use strict';

    var searchPage = '/charms/search.html';

    var lastSearch = null;

    // Custom event raised after the fragment is appended to the DOM.
    WinJS.Application.addEventListener('fragmentappended', function handler(e) {
        if (e.location === searchPage) { fragmentLoad(e.fragment, e.state); }
    });

    try {
        Windows.ApplicationModel.Search.SearchPane.getForCurrentView().addEventListener('querysubmitted', querySubmitted, false);
    } catch (e) { }

    function activated(e) {
        if (e.kind === Windows.ApplicationModel.Activation.ActivationKind.search) {
            WinJS.Navigation.navigate(searchPage, { queryText: e.queryText });
        }
    }

    function updateForLayout(lv, layout) {
        updateTitle(document.body);
        var layoutState = Windows.UI.ViewManagement.ApplicationLayoutState;
        if (layout === layoutState.snapped) {
            lv.layout = new WinJS.UI.ListLayout();
        } else {
            lv.layout = new WinJS.UI.GridLayout();
        }
        lv.refresh();
    }

    function layoutChanged(e) {
        var list = document.querySelector('.searchResults');
        if (list) {
            var lv = WinJS.UI.getControl(list);
            updateForLayout(lv, e.layout);
        }
    }

    function updateTitle(elements) {
        if (lastSearch) {
            var appLayout = null;
            try {
                var appLayout = Windows.UI.ViewManagement.ApplicationLayout.getForCurrentView();
            } catch (ex) { }

            if (appLayout && Windows.UI.ViewManagement.ApplicationLayout.value === Windows.UI.ViewManagement.ApplicationLayoutState.snapped) {
                elements.querySelector('.pageTitle').innerHTML = 'TrialTool';
                elements.querySelector('.pageSubtitle').innerHTML = "&#148;" + toStaticHTML(lastSearch) + "&#148;";
            }
            else {
                elements.querySelector('.pageTitle').innerHTML = 'TrialTool';
                elements.querySelector('.pageSubtitle').innerHTML = 'Results for &#148;' + toStaticHTML(lastSearch) + '&#148;';
            }
        }
    }

    function handleQuery(elements, e) {
        lastSearch = e.queryText;
        updateTitle(elements);

        searchData(e.queryText).then(function (results) {
            var lv = WinJS.UI.getControl(elements.querySelector('.searchResults'));
            lv.dataSource = results;
            document.body.focus();
        });
    }

    function fragmentLoad(elements, options) {
        WinJS.UI.process(elements.querySelector('.itemTemplate'))
            .then(function (template) {
            search.searchItemTemplate = template.element;

            return WinJS.UI.processAll(elements);
        }).then(function () {
            try {
                var appLayout = Windows.UI.ViewManagement.ApplicationLayout.getForCurrentView();
                if (appLayout) {
                    appLayout.addEventListener('layoutchanged', layoutChanged);
                }
                var lv = WinJS.UI.getControl(elements.querySelector('.searchResults'));
                updateForLayout(lv, Windows.UI.ViewManagement.ApplicationLayout.value);
            } catch (ex) { }
            handleQuery(elements, options);
        });
    }

    // If the application is not running when a query is received, navigate to the search page.
    function querySubmitted(e) {
        if (WinJS.Navigation.location !== searchPage) {
            WinJS.Navigation.navigate(searchPage, e);
        }
        else {
            handleQuery(document.body, e);
        }
    }

    function itemInvoked(e) {
        WinJS.Navigation.navigate('/html/splitPage.html', searchResults[e.detail.itemIndex]);
    }

    function searchData(queryText) {
        function colorfy(find, str) {
            return str.replace(new RegExp(find, 'g'), '<mark>' + find + '</mark>');
        }

        return new WinJS.Promise(function (complete, error) {
            WinJS.xhr({ "url": "/data/index.js" }).then(function (response) {
                var markedArray = [];
                searchResults = JSON.parse(response.responseText)
                searchResults = searchResults.filter(function (e) {
                    return !(e.name.indexOf(lastSearch) === -1 && e.desc.indexOf(lastSearch) === -1);
                });
                searchResults.forEach(function (e, i, a) {
                    markedArray.push({
                        "name": colorfy(queryText, e.name),
                        "desc": colorfy(queryText, e.desc),
                        "img": e.img
                    });
                });
                complete(markedArray);
            }, function (res) {
                error(res);
            });
        });
    }

    Windows.UI.WebUI.WebUIApplication.addEventListener('activated', activated);
    var searchResults = [];
    WinJS.Namespace.define('search', {
        fragmentLoad: fragmentLoad,
        itemInvoked: itemInvoked
    });

})();
